from typing import List, Optional
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, delete
from models.issue import ComplianceItemIssue
from schemas.issue import IssueCreate, IssueUpdate

async def get_issue(db: AsyncSession, issue_id: UUID) -> Optional[ComplianceItemIssue]:
    """Get a single issue by ID."""
    stmt = select(ComplianceItemIssue).where(ComplianceItemIssue.id == issue_id)
    result = await db.execute(stmt)
    return result.scalar_one_or_none()

async def get_issues_by_plan(db: AsyncSession, plan_id: UUID, skip: int = 0, limit: int = 100) -> List[ComplianceItemIssue]:
    """Get all issues for a specific assessment plan."""
    stmt = (
        select(ComplianceItemIssue)
        .where(ComplianceItemIssue.plan_id == plan_id)
        .offset(skip)
        .limit(limit)
    )
    result = await db.execute(stmt)
    return result.scalars().all()

async def create_issue(db: AsyncSession, issue: IssueCreate) -> ComplianceItemIssue:
    """Create a new issue."""
    db_issue = ComplianceItemIssue(**issue.model_dump())
    db.add(db_issue)
    await db.commit()
    await db.refresh(db_issue)
    return db_issue

async def update_issue(
    db: AsyncSession, db_issue: ComplianceItemIssue, issue: IssueUpdate
) -> ComplianceItemIssue:
    """Update an existing issue."""
    update_data = issue.model_dump(exclude_unset=True)
    for field, value in update_data.items():
        setattr(db_issue, field, value)
    
    db.add(db_issue)
    await db.commit()
    await db.refresh(db_issue)
    return db_issue

async def delete_issue(db: AsyncSession, db_issue: ComplianceItemIssue) -> None:
    """Delete an issue."""
    db.delete(db_issue)
    await db.commit()

async def delete_issues(db: AsyncSession, issue_ids: List[UUID]) -> int:
    """
    批量删除问题项
    
    Args:
        db: 数据库会话
        issue_ids: 要删除的问题项ID列表
        
    Returns:
        int: 实际删除的记录数
        
    Raises:
        Exception: 删除操作失败时抛出异常
    """
    if not issue_ids:
        return 0
    
    try:
        result = await db.execute(
            delete(ComplianceItemIssue).where(ComplianceItemIssue.id.in_(issue_ids))
        )
        await db.commit()
        deleted_count = result.rowcount
        return deleted_count
    except Exception as e:
        await db.rollback()
        raise
